<?php
declare(strict_types=1);

namespace app\model;

/**
 * 栏目模型
 */
class Category extends Base
{
    protected $schema = [
        "id"          => "int",
        "parent_id"   => "int",
        "name"        => "varchar",
        "url"         => "varchar",
        "route"       => "varchar",
        "module"      => "varchar",
        "type"        => "int",
        "is_nav"      => "int",
        "remark"       => "varchar",
        "sort"        => "int",
        'status'      => "varchar",
        "title"       => "varchar",
        "keywords"    => "varchar",
        "description" => "varchar",
        "is_blank"    => "int",
        "create_time" => "int",
        "update_time" => "int"
    ];

    // 获取列表
    public static function getList(array $param = [])
    {
        $where = [];

        if (isset($param['is_nav']) ) {
            $where[] = ['is_nav', '=', (int) $param['is_nav']];
        }

        if (isset($param['type']) ) {
            $where[] = ['type', '=', (int) $param['type']];
        }

        $order = isset($param['order']) ? (string) $param['order'] : "sort ASC,id DESC";

        return self::where($where)->field("id,parent_id,name,name_en,url,route,module,type,is_nav,sort,title,is_blank,create_time")->order($order)->select();
    }

    // 导航状态修改 1,显示; 0,不显示
    public static function navStaus(int $id)
    {
        try {
            $info         = self::find($id);
            $info->is_nav = 1 - $info['is_nav'];
            $info->save();
            return json(['code' => 0, 'msg' => '修改成功!', 'is_nav'=>$info->is_nav]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    // 选择上级栏目列表
    public static function getParentList()
    {
        $list = self::where('type', '<>', 0)->field("id,parent_id,name")->select();

        $treeList = list_tree($list, 'id', 'parent_id');

        return $treeList;
    }

    //
    public static function getTreeList()
    {
        $list = self::where('type', 0)->field("id,parent_id,name,type")->select();

        $treeList = list_tree($list, 'id', 'parent_id');

        return $treeList;
    }

    // 获取文章栏目列表
    public static function getArticleList()
    {
        return self::where('type', 0)->where('module', 'article')->field("id,parent_id,name,name_en,url,route")->select();
    }

    public static function info(int $id)
    {
        return self::where('id', $id)->field("id,parent_id,name,name_en,url,title,keywords,description")->find();
    }
}
